<template>
  <div class="servers-container">
    <div class="header">
      <div class="header-left">
        <h2>服务器管理</h2>
        <el-tag type="info" class="server-count">共 {{ serverList.length }} 台服务器</el-tag>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog" icon="el-icon-plus">添加服务器</el-button>
        <el-button @click="refreshServers" icon="el-icon-refresh">刷新</el-button>
      </div>
    </div>
    
    <el-card class="filter-card" shadow="never">
      <div class="filter-content">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="服务器名称">
            <el-input v-model="filterForm.name" placeholder="请输入服务器名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="操作系统">
            <el-select v-model="filterForm.osType" placeholder="请选择操作系统" clearable>
              <el-option label="Windows" value="WINDOWS"></el-option>
              <el-option label="Linux" value="LINUX"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="applyFilter" icon="el-icon-search">搜索</el-button>
            <el-button @click="resetFilter" icon="el-icon-refresh-left">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    
    <el-table 
      :data="paginatedServers" 
      style="width: 100%" 
      border
      class="servers-table"
      v-loading="loading"
    >
      <el-table-column prop="name" label="服务器名称" width="150" show-overflow-tooltip></el-table-column>
      <el-table-column prop="hostname" label="主机名" width="150" show-overflow-tooltip></el-table-column>
      <el-table-column prop="port" label="端口" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="osType" label="操作系统" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.osType === 'WINDOWS' ? 'primary' : 'success'">
            {{ scope.row.osType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="osVersion" label="系统版本" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)" icon="el-icon-edit">编辑</el-button>
          <el-button 
            size="mini" 
            type="primary" 
            @click="testConnection(scope.row)" 
            icon="el-icon-connection"
            :loading="testConnectionLoading"
          >
            测试
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)" icon="el-icon-delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredServers.length"
      >
      </el-pagination>
    </div>
    
    <!-- 创建/编辑服务器对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="handleDialogClose"
      class="server-dialog"
    >
      <el-form
        :model="serverForm"
        :rules="serverFormRules"
        ref="serverForm"
        label-width="100px"
        class="server-form"
      >
        <el-form-item label="服务器名称" prop="name">
          <el-input v-model="serverForm.name" placeholder="请输入服务器名称"></el-input>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="主机名" prop="hostname">
              <el-input v-model="serverForm.hostname" placeholder="请输入主机名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="端口" prop="port">
              <el-input v-model.number="serverForm.port" placeholder="请输入端口"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="serverForm.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="serverForm.password" type="password" placeholder="请输入密码" show-password></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="私钥" prop="privateKey">
          <el-input 
            v-model="serverForm.privateKey" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入私钥内容（可选）"
          ></el-input>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="操作系统" prop="osType">
              <el-select v-model="serverForm.osType" placeholder="请选择操作系统" style="width: 100%;">
                <el-option label="Windows" value="WINDOWS"></el-option>
                <el-option label="Linux" value="LINUX"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系统版本" prop="osVersion">
              <el-input v-model="serverForm.osVersion" placeholder="请输入系统版本"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="描述" prop="description">
          <el-input v-model="serverForm.description" type="textarea" :rows="3" placeholder="请输入描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import axios from 'axios'

export default {
  name: 'Servers',
  data() {
    return {
      dialogVisible: false,
      dialogTitle: '添加服务器',
      isEdit: false,
      loading: false,
      testConnectionLoading: false,
      filterForm: {
        name: '',
        osType: ''
      },
      pagination: {
        currentPage: 1,
        pageSize: 20  // 修改默认页面大小为20
      },
      serverForm: {
        id: null,
        name: '',
        hostname: '',
        port: 22,
        username: '',
        password: '',
        privateKey: '',
        osType: 'LINUX',
        osVersion: '',
        description: ''
      },
      serverFormRules: {
        name: [
          { required: true, message: '请输入服务器名称', trigger: 'blur' }
        ],
        hostname: [
          { required: true, message: '请输入主机名', trigger: 'blur' }
        ],
        port: [
          { required: true, message: '请输入端口', trigger: 'blur' },
          { type: 'number', message: '端口必须为数字', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        osType: [
          { required: true, message: '请选择操作系统', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    // 重新定义计算属性，避免与data中的属性冲突
    serverList() {
      return this.$store.state.servers.servers || []
    },
    filteredServers() {
      let result = this.serverList;
      
      // 应用过滤条件
      if (this.filterForm.name) {
        result = result.filter(server => 
          server.name.toLowerCase().includes(this.filterForm.name.toLowerCase())
        );
      }
      
      if (this.filterForm.osType) {
        result = result.filter(server => server.osType === this.filterForm.osType);
      }
      
      return result;
    },
    paginatedServers() {
      // 应用分页
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      return this.filteredServers.slice(start, end);
    }
  },
  async created() {
    await this.refreshServers();
  },
  methods: {
    ...mapActions('servers', ['fetchServers', 'createServer', 'updateServer', 'deleteServer']),
    async refreshServers() {
      this.loading = true;
      try {
        await this.fetchServers();
      } catch (error) {
        this.$message.error(error.message || '刷新失败');
      } finally {
        this.loading = false;
      }
    },
    showCreateDialog() {
      this.dialogTitle = '添加服务器';
      this.isEdit = false;
      this.serverForm = {
        id: null,
        name: '',
        hostname: '',
        port: 22,
        username: '',
        password: '',
        privateKey: '',
        osType: 'LINUX',
        osVersion: '',
        description: ''
      };
      this.dialogVisible = true;
    },
    showEditDialog(server) {
      this.dialogTitle = '编辑服务器';
      this.isEdit = true;
      this.serverForm = { ...server };
      this.dialogVisible = true;
    },
    handleDialogClose() {
      this.$refs.serverForm.resetFields();
    },
    applyFilter() {
      this.pagination.currentPage = 1;
    },
    resetFilter() {
      this.filterForm = {
        name: '',
        osType: ''
      };
      this.pagination.currentPage = 1;
    },
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.pagination.currentPage = 1;
    },
    handleCurrentChange(page) {
      this.pagination.currentPage = page;
    },
    async handleSave() {
      this.$refs.serverForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.isEdit) {
              await this.updateServer({
                id: this.serverForm.id,
                serverData: this.serverForm
              });
              this.$message.success('服务器更新成功');
            } else {
              await this.createServer(this.serverForm);
              this.$message.success('服务器创建成功');
            }
            this.dialogVisible = false;
            await this.refreshServers();
          } catch (error) {
            this.$message.error(error.message || '操作失败');
          }
        }
      });
    },
    async testConnection(server) {
      this.testConnectionLoading = true;
      try {
        this.$message.info(`正在测试连接到 ${server.name}...`);
        
        // 调用后端API测试连接
        const response = await axios.post(`/api/servers/${server.id}/test-connection`);
        const result = response.data;
        
        if (result.success) {
          this.$message.success(`连接到 ${server.name} 成功！系统信息: ${result.systemInfo || '无'}`);
        } else {
          this.$message.error(`连接到 ${server.name} 失败: ${result.message}`);
        }
      } catch (error) {
        this.$message.error(`测试连接到 ${server.name} 时发生错误: ${error.message}`);
      } finally {
        this.testConnectionLoading = false;
      }
    },
    async handleDelete(server) {
      this.$confirm('此操作将永久删除该服务器, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.deleteServer(server.id);
          this.$message.success('删除成功');
          await this.refreshServers();
        } catch (error) {
          this.$message.error(error.message || '删除失败');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    }
  }
}
</script>

<style scoped>
.servers-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.server-count {
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.filter-content {
  padding: 20px 0;
}

.filter-form ::v-deep .el-form-item {
  margin-bottom: 0;
}

.servers-table {
  margin-bottom: 20px;
}

.servers-table ::v-deep .el-table__row:hover {
  background-color: #f5f7fa;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.server-dialog ::v-deep .el-dialog__body {
  padding: 20px;
}

.server-form ::v-deep .el-form-item {
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-left {
    justify-content: center;
  }
  
  .header-right {
    justify-content: center;
  }
  
  .filter-content {
    padding: 15px 0;
  }
  
  .filter-form ::v-deep .el-form-item {
    margin-bottom: 15px;
    width: 100%;
  }
  
  .filter-form ::v-deep .el-form-item__content {
    width: 100%;
  }
  
  .filter-form ::v-deep .el-input,
  .filter-form ::v-deep .el-select {
    width: 100% !important;
  }
}
</style>